package bank;


import java.io.IOException;
import java.rmi.RemoteException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import beans.PageBean;
import beans.PinAutomaatBean;
import common.BankException;

public class Storten extends HttpServlet
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void init()
	{
		System.out.println("Storten.init()");
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		System.out.println("Storten.doGet()");
	
		UberClass uberclass = new UberClass(request, response);
		
		PageBean pb = new PageBean("pinautomaat/Storten.jsp");
		request.setAttribute("page", pb);
		
		uberclass.startOutput();
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		System.out.println("Storten.doPost()");
		PinAutomaatBean pab = new PinAutomaatBean();
		
		UberClass uberclass = new UberClass(request, response);
		
		String submit = request.getParameter("submit");
		if(submit.equals("Storten"))
		{
			storten(request, uberclass, pab);
		}
			
		PageBean pb = new PageBean("pinautomaat/Storten.jsp");
		request.setAttribute("page", pb);
		request.setAttribute("pab", pab);
		uberclass.startOutput();
	}
	
	public void storten(HttpServletRequest r, UberClass u, PinAutomaatBean pab)
	{
		String bedrag = r.getParameter("bedrag");
		boolean error=false;
		Double bdr = null;
		
		try
		{
			 bdr = Double.parseDouble(bedrag);
		}
		catch(Exception e)
		{
			u.error("Er moet een geldig bedrag ingevuld worden");
			error=true;
		}
					
		if(bedrag.equals("")|| bedrag.substring(0,1).equals("-"))
		{
			error=true;
			u.error("Er moet een geldig bedrag ingevuld worden");
		}
		if(!error)
		{
			try 
			{
				u.getOffice().transfer(null, bdr.doubleValue());
				u.getOffice().sync();
				System.out.println("<<SYNC>>");
				pab.populate(r);
				r.setAttribute("b_pab", pab);
			}
			catch (BankException e) 
			{
				u.error("Er is een fout opgetreden tijdens het storten van het geld " + e);
			}
		}
		
		pab.put( "includeSubPage", "yes" );
		pab.put( "subPage", "/pinautomaat/storten_result.jsp" );
	
	}
}
